<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;
use WindowsAzure\Queue\Models\CreateQueueOptions;
use WindowsAzure\Queue\Models\PeekMessagesOptions;

use Config;
use Request;
use Log;
class QueueController extends Controller
{

    var $queue;

    public function __construct()
    {
        Log::info(session('access-key'));

        if (session()->has('account') && session()->has('access-key')) {
            $connection = "DefaultEndpointsProtocol=https;AccountName=" . session('account') . ";AccountKey=" . session('access-key');
            $this->queue = ServicesBuilder::getInstance()->createQueueService($connection);
        }
        else {
            return Redirect::to('/')->send();
        }
    }


    /*
     * Main Index page of the Queue
     *
     */
    public function index()
    {
        $data['title'] = "Queue";
        $data['heading'] = "Queue";
        return view('queue', $data);
    }

    public function create()
    {
        $data['title'] = "Queue";
        $data['heading'] = "Create Queue";
        return view('addqueue', $data);
    }

    public function delete()
    {
        $data['title'] = "Queue";
        $data['heading'] = "Delete Queue";
        return view('deletequeue', $data);
    }

    public function createQueueProcess($queue)
    {
        $data = Request::all();
        $fields = count($data) / 2;
        $createQueueOptions = new CreateQueueOptions();
        for ($i = 1; $i <= $fields; $i++) {
            $createQueueOptions->addMetaData($data['key-' . $i], null, $data['value-' . $i]);
        }
        try {
            // Create queue.
            $this->queue->createQueue($queue, $createQueueOptions);
            $data['statusCode'] = 200;
            return json_encode($data);
        }
        catch (ServiceException $e) {
            // Handle exception based on error codes and messages.
            // Error codes and messages are here:
            // http://msdn.microsoft.com/library/azure/dd179446.aspx
            $code = $e->getCode();
            $error_message = $e->getMessage();
            $data['statusCode'] = 400;
            $data['errorMessage'] = $error_message;
            return json_encode($data);
        }
    }

    /**
     * This function peeks the messages from the queue
     * @param $queueName
     * @param $numMessages
     * @return \Illuminate\View\View
     */
    public function queuePeekMessages($queueName, $numMessages)
    {
        $message_options = new PeekMessagesOptions();
        $message_options->setNumberOfMessages($numMessages); // Default value is 1.

        try {
            $peekMessagesResult = $this->queue->peekMessages($queueName, $message_options);
            $messages['messages'] = $peekMessagesResult->getQueueMessages();
            $data['statusCode'] = 200;
            $data['view'] = view('renders.queuemessages', $messages)->render();
            return json_encode($data);
        }
        catch (ServiceException $e) {
            // Handle exception based on error codes and messages.
            // Error codes and messages are here:
            // http://msdn.microsoft.com/library/azure/dd179446.aspx
            $code = $e->getCode();
            $error_message = $e->getMessage();
            $data['statusCode'] = 400;
            $data['errorMessage'] = $error_message;
            return json_encode($data);
        }
    }


    /**
     * This function is used to add the message to the queue
     *
     * @return string
     */
    public function addMessage()
    {
        $data = Request::all();
        try {
            // Create message.
            $builder = new ServicesBuilder();
            $this->queue->createMessage($data['name'], $data['message']);
            $data['statusCode'] = 200;
            return json_encode($data);

        }
        catch (ServiceException $e) {
            // Handle exception based on error codes and messages.
            // Error codes and messages are here:
            // http://msdn.microsoft.com/library/azure/dd179446.aspx
            $code = $e->getCode();
            $error_message = $e->getMessage();
            $data['statusCode'] = 400;
            $data['errorMessage'] = $error_message;
            return json_encode($data);
        }
    }

    public function dequeueMessage()
    {
        $data = Request::all();
        // Get message.
        $listMessagesResult = $this->queue->listMessages($data['queue']);
        $messages = $listMessagesResult->getQueueMessages();
        $message = $messages[0];

        /* ---------------------
            Process message.
           --------------------- */

// Get message ID and pop receipt.
        $messageId = $message->getMessageId();
        $popReceipt = $message->getPopReceipt();

        try {
            // Delete message.
            $this->queue->deleteMessage($data['queue'], $messageId, $popReceipt);
            $data['statusCode'] = 200;
            return json_encode($data);
        }
        catch (ServiceException $e) {
            // Handle exception based on error codes and messages.
            // Error codes and messages are here:
            // http://msdn.microsoft.com/library/azure/dd179446.aspx
            $code = $e->getCode();
            $error_message = $e->getMessage();
            $data['statusCode'] = 400;
            $data['errorMessage'] = $error_message;
            return json_encode($data);
        }
    }


    public function deleteQueue()
    {
        $data = Request::all();
        try {
            // Delete queue.
            $this->queue->deleteQueue($data['queue']);
            $data['statusCode'] = 200;
            return json_encode($data);
        }
        catch (ServiceException $e) {
            // Handle exception based on error codes and messages.
            // Error codes and messages are here:
            // http://msdn.microsoft.com/library/azure/dd179446.aspx
            $code = $e->getCode();
            $error_message = $e->getMessage();
            $data['statusCode'] = 400;
            $data['errorMessage'] = $error_message;
            return json_encode($data);
        }catch(Exception $e){
            $error_message = $e->getMessage();
            $data['statusCode'] = 400;
            $data['errorMessage'] = $error_message;
            return json_encode($data);
        }
    }

}
